package net.huashitong.supervision.task.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysLoginDao;
import com.sirdc.modules.sys.dao.SysUserDao;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.DeptService;
import com.sirdc.modules.sys.service.SysDeptService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.task.dao.TaskSubDao;
import net.huashitong.supervision.task.dao.TaskUnitDao;
import net.huashitong.supervision.task.dataBean.TaskUnitBean;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.TaskMainFilter;
import net.huashitong.supervision.task.filter.TaskSubFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.filter.TaskUserFilter;
import net.huashitong.supervision.task.util.HolidayUtils;
import net.huashitong.supervision.task.util.WeekDayUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/8/6
 * Time: 18:17
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service
public class TaskUnitService extends StringPKService<TaskUnit> {
    @Autowired
    @Lazy(true)
    private SysTableService tableService;
    @Autowired
    @Lazy(true)
    private TaskMainService taskMainService;
    @Autowired
    private TaskSubDao taskSubDao;
    @Autowired
    @Lazy(true)
    private TaskSubService taskSubService;
    @Autowired
    @Lazy(true)
    private TaskUserService taskUserService;
    @Autowired
    private TaskUnitDao taskUnitDao;
    @Autowired
    private SysLoginDao sysLoginDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    @Lazy(true)
    private TaskLogNewService taskLogNewService;
    @Autowired
    @Lazy(true)
    private SysDeptService sysDeptService;
    @Autowired
    @Lazy(true)
    private DeptService deptService;
    @Autowired
    @Lazy(true)
    private CopeToService copeToService;
    @Autowired
    @Lazy(true)
    private TaskBackNewService taskBackNewService;
    @Autowired
    @Lazy(true)
    private HastenMessageService hastenMessageService;
    @Autowired
    private SMSUtilService smsUtilService;
    @Autowired
    private TimeLimitService timeLimitService;

    @Override
    protected BaseDao<TaskUnit, String> getDao() {
        return taskUnitDao;
    }

    @Override
    protected void beforeSave(TaskUnit obj) {
        obj.setSysId(tableService.updateMaxSysId("t_task_unit", null));
    }

    SimpleDateFormat simdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat simdate1 = new SimpleDateFormat("yyyy-MM-dd");
    private static String[] parsePatterns = {"yyyy-MM-dd"};

    public void save(TaskUnit obj, String userId) {
        Date date = new Date();
        String date1 = HolidayUtils.sdf1.format(date);
        String time = HolidayUtils.sdf2.format(date);
        obj.setSysId(tableService.updateMaxSysId("t_task_unit", null));
        obj.setCreateUser(userId);
        obj.setUpdUser(userId);
        obj.setCreateDate(date1);
        obj.setCreateTime(time);
        obj.setUpdDate(date1);
        obj.setUpdTime(time);
        getDao().save(obj);
    }

    public List<TaskUnit> getBySubId(String taskSubId) {
        return taskUnitDao.getBySubId(taskSubId);
    }

    public int getCountByType(String taskMainId, String type) {
        return taskUnitDao.getCountByType(taskMainId, type);
    }

    public int getCountByStatus(String taskMain, String status) {
        return taskUnitDao.getCountByStatus(taskMain, status);
    }

    public void batchDeleteIds(List<String> ids) {
        //删除当前任务的流程记录和反馈信息
        List<String> taskUnitIds = new ArrayList<>();
        for (String id : ids) {
            List<TaskUnit> taskUnits = this.getByMainId(id);
            if (ObjectUtils.isNotBlank(taskUnits)) {
                for (TaskUnit taskUnit : taskUnits) {
                    taskUnitIds.add(taskUnit.getSysId());
                }
            }
        }
        if (taskUnitIds.size() > 0) {
            //删除日志
            taskLogNewService.deleteByUnitIds(taskUnitIds);
            //删除反馈
            taskBackNewService.deleteByUnitIds(taskUnitIds);
            //删除催办
            hastenMessageService.deleteByUnitIds(taskUnitIds);
            taskUnitDao.batchDeleteIds(ids);
        }
    }

    public List<TaskUnit> queryFilter(TaskUnitFilter filter) {
        if (StringUtils.isNotBlank(filter.getTaskMainId())) {
            //判断当前任务是否是未审批
            TaskMain taskMain = taskMainService.getById(filter.getTaskMainId());
            if ("0".equals(taskMain.getStatus())) {
                filter.setStatus("0");
            }
            //如果有新反馈，只显示已经反馈的单位
            if ("3".equals(taskMain.getStatus())) {
                filter.setType("2");
            }
        }
        return taskUnitDao.queryFilter(filter);
    }

    /**
     * 查询排除内部事务督查任务后的任务数
     *
     * @param filter
     * @return
     */
    public List<TaskUnitBean> queryByCategory(TaskUnitFilter filter) {
        return taskUnitDao.queryByCategory(filter);
    }

    /**
     * 签收批转任务
     *
     * @return
     */
   /* public String saveSignTask(TaskUnitFilter filter) {
        TaskUnit taskUnit = this.getById(filter.getSysId());
//        taskUnit.setUserId(filter.getUserId());
        taskUnit.setType("1");
        this.update(taskUnit);
        if (filter.getTaskUserList()!=null&&filter.getTaskUserList().size()>0){
            List<TaskUser> list = filter.getTaskUserList();
            for (TaskUser taskUser : list) {
                taskUser.setTaskUnitId(taskUnit.getSysId());
                taskUserService.save(taskUser);
            }
        }
        //改变主任务中单位任务状态详情
        TaskMain taskMain = taskMainService.getById(taskUnit.getTaskMainId());
        int t0 = this.getCountByType(taskMain.getSysId(),"0");
        int t1 = this.getCountByType(taskMain.getSysId(),"1");
        int t2 = this.getCountByType(taskMain.getSysId(),"2");
        int t3 = this.getCountByType(taskMain.getSysId(),"3");
        int t4 = this.getCountByType(taskMain.getSysId(),"4");
        int o = this.getCountByStatus(taskMain.getSysId(),"1");
        taskMain.setTypeExplain("待签收: " + t0 + "; 待反馈: " + (t1) + "; 已反馈: " + t2 + "; 重办: " + t3 + "; 完成: " + t4);
        taskMain.setOverdueExplain("逾期单位任务: " + o);
        taskMainService.update(taskMain);
        return "200";
    }*/
    public List<TaskUnit> getByMainId(String taskMainId) {
        return taskUnitDao.getByMainId(taskMainId);
    }

    public List<TaskUnit> getByMainIdDel(String taskMainId) {
        return taskUnitDao.getByMainIdDel(taskMainId);
    }

    public List<SysUser> queryEndorseList(String taskUnitId, String userId) {
        String roleId = "";
        if (StringUtils.isBlank(userId)) {
            roleId = SysUserUtils.getRoleId();
            userId = SysUserUtils.getUserId();
        } else {
            SysLogin login = sysLoginDao.getById(userId);
            roleId = login.getRoleId();
        }
        SysLogin login = sysLoginDao.getById(userId);
        SysUserFilter filter = new SysUserFilter();
        filter.setRoleId("03");
        filter.setDeptId(login.getDeptId());
        List<SysLogin> sysLoginList03 = sysLoginDao.queryUserLoginByRoleDept(filter);
        filter.setRoleId("04");
        List<SysLogin> sysLoginList04 = sysLoginDao.queryUserLoginByRoleDept(filter);
        List<SysLogin> loginList = new ArrayList<>();
        if ("02".equals(roleId)) {
            loginList.addAll(sysLoginList03);
            loginList.addAll(sysLoginList04);
        }
        if ("03".equals(roleId)) {
            loginList.addAll(sysLoginList04);
        }
        List<SysUser> userList = new ArrayList<>();
        for (SysLogin sysLogin : loginList) {
            SysUser user = sysUserDao.getById(sysLogin.getSysId());
            if ("03".equals(user.getState())) {
                continue;
            }
            userList.add(user);
        }
        //查询当前单位人员接收到改任务的人

        //查询当前单位人员接收到改任务的人
        List<TaskUser> taskUsers = taskUserService.getByTaskUnitId(taskUnitId);
        List<SysUser> users = new ArrayList<SysUser>();

        if (ObjectUtils.isNotBlank(taskUsers)) {
            //将能批转的单位人员遍历
            List<SysUser> userTasks = new ArrayList<>();
            for (TaskUser taskUser : taskUsers) {
                SysUser user1 = sysUserDao.getById(taskUser.getUnitUserId());
                userTasks.add(user1);
            }
            users.addAll(userList);
            users.removeAll(userTasks);
        } else {
            users.addAll(userList);
        }
        return users;
    }

    public List<TaskUnit> getUnDoneUnit(TaskUnitFilter filter) {
        return taskUnitDao.unDoneTask(filter);
    }

    public List<TaskUnit> getNowUser(TaskUnitFilter filter) {
        return taskUnitDao.getNowUser(filter);
    }

    public List<TaskUnit> getUnDoneUser(TaskUnitFilter filter) {
        return taskUnitDao.getUnDoneUser(filter);
    }

    public List<TaskUnit> getBySubIdAndUnitType(String taskSubId, String unitType, String timeRound) {
        return taskUnitDao.getBySubIdAndUnitType(taskSubId, unitType, timeRound);
    }

    public String saveTaskUser(TaskUnitFilter filter) {
        String userId = "";
        if (StringUtils.isNotBlank(filter.getUserId())) {
            userId = filter.getUserId();
        } else {
            userId = SysUserUtils.getUserId();
        }
        SysUser user = sysUserDao.getById(userId);
        SysLogin sysLogin = sysLoginDao.getById(userId);
        String roleId = sysLogin.getRoleId();
        TaskUnit taskUnit = taskUnitDao.getById(filter.getSysId());
        TaskMain taskMain = taskMainService.getById(taskUnit.getTaskMainId());
        //取出批转人员集合
        String taskUsers = filter.getTaskUsers();
        if (StringUtils.isNotBlank(taskUsers)) {
            String[] strings = taskUsers.split(",");

           /* for (String s : strings) {
                //查询当前人员是否有已有任务
                List<TaskUser> taskUserList = taskUserService.getByTaskUnitIdAndUnitUserId(filter.getSysId(), s);
                if (ObjectUtils.isNotBlank(taskUserList)) {
                    continue;
                }
            }*/

            //如果是单位批转，将单位任务状态改为待反馈
            if ("02".equals(roleId)) {
                for (String s : strings) {
                    //查询当前人员是否有已有任务
                    List<TaskUser> taskUserList = taskUserService.getByTaskUnitIdAndUnitUserId(filter.getSysId(), s);
                    if (ObjectUtils.isNotBlank(taskUserList)) {
                        continue;
                    } else {
                        SysUser user1 = sysUserDao.getById(s);

                        TaskUser taskUser = new TaskUser();
                        taskUser.setStatus("0");
                        taskUser.setUnitUserId(s);
                        taskUser.setTaskUnitId(filter.getSysId());
                        taskUser.setTaskSubId(taskUnit.getTaskSubId());
                        taskUser.setUserName(user1.getName());
                        //批转后设置人员任务为待办
                        taskUser.setStatus("0");
                        taskUser.setState("0");
                        taskUserService.save(taskUser, userId);
                        //给批转人员送短信提醒
                        smsUtilService.taskUserSMS(taskUnit, user1);
                        //添加任务日志
                        TaskLogNew taskLogNew = new TaskLogNew();
                        taskLogNew.setTaskUnitId(filter.getSysId());
                        taskLogNew.setUserId(s);
                        String content = user.getName() + "签收,批转给" + user1.getName();
                        taskLogNew.setContent(content);
                        taskLogNewService.save(taskLogNew, userId);
                    }
                }
                if ("5".equals(taskUnit.getType())) {
                    taskUnit.setType("1");
                    //单位任务转为在办
                }
                taskUnit.setState("1");
                this.update(taskUnit);
            } else {
                //分管批转
                for (String s : strings) {
                    //查询当前人员是否有已有任务
                    List<TaskUser> taskUserList = taskUserService.getByTaskUnitIdAndUnitUserId(filter.getSysId(), s);
                    if (ObjectUtils.isNotBlank(taskUserList)) {
                        continue;
                    } else {
                        SysUser user1 = sysUserDao.getById(s);
                        smsUtilService.taskUserSMS(taskUnit, user1);
                        TaskUser taskUser = new TaskUser();
                        taskUser.setStatus("0");
                        taskUser.setUnitUserId(s);
                        taskUser.setTaskUnitId(filter.getSysId());
                        taskUser.setTaskSubId(taskUnit.getTaskSubId());
                        taskUser.setUserName(user1.getName());
                        //分管批转将批转出去的任务状态设置为待办
                        taskUser.setState("0");
                        taskUserService.save(taskUser, userId);
                        //添加任务日志
                        TaskLogNew taskLogNew = new TaskLogNew();
                        taskLogNew.setTaskUnitId(filter.getSysId());
                        taskLogNew.setUserId(s);
                        String content = user.getName() + "签收,批转给" + user1.getName();
                        taskLogNew.setContent(content);
                        taskLogNewService.save(taskLogNew, userId);
                    }
                }
                List<TaskUser> taskUserList = taskUserService.getByTaskUnitIdAndUnitUserId(filter.getSysId(), userId);
                //将自己任务设置为已批转
                taskUserList.get(0).setStatus("1");
                //将自己任务设置为已办办
                taskUserList.get(0).setState("1");
                taskUserService.update(taskUserList.get(0));
            }
            int t0 = taskUnitDao.getCountByType(taskMain.getSysId(), "0");
            int t1 = taskUnitDao.getCountByType(taskMain.getSysId(), "1");
            int t2 = taskUnitDao.getCountByType(taskMain.getSysId(), "2");
            int t3 = taskUnitDao.getCountByType(taskMain.getSysId(), "3");
            int t4 = taskUnitDao.getCountByType(taskMain.getSysId(), "4");
            int o = taskUnitDao.getCountByStatus(taskMain.getSysId(), "10");
            taskMain.setTypeExplain("待签收: " + t0 + "; 待反馈: " + t1 + "; 已反馈: " + t2 + "; 重办: " + t3 + "; 完成: " + t4);
            taskMain.setOverdueExplain("逾期单位任务: " + o);
            taskMainService.update(taskMain);
            return "200";
        } else {
            return "500";
        }
    }

    public List<Map> getBackUserList(String taskUnitId) {
        TaskUnit taskUnit = taskUnitDao.getById(taskUnitId);
        List<Map> list = new ArrayList<>();
        if ("2".equals(taskUnit.getUnitType()) && "02".equals(SysUserUtils.getRoleId())) {
            //如果该单位任务是协办单位返回当前任务主办单位
            List<TaskUnit> unitList = taskUnitDao.getBySubId(taskUnit.getTaskSubId());
            for (TaskUnit unit : unitList) {
                if ("1".equals(unit.getUnitType())) {
                    SysDept dept = sysDeptService.getById(unit.getDeptId());
                    Map<String, String> map = new HashMap();
                    map.put("userId", dept.getSysId());
                    map.put("username", dept.getDeptName());
                    list.add(map);
                }
            }
        }
        if (!"02".equals(SysUserUtils.getRoleId())) {
            //如果是经办
            if ("04".equals(SysUserUtils.getRoleId())) {
                TaskUserFilter filter = new TaskUserFilter();
                filter.setTaskUnitId(taskUnitId);
                filter.setUnitUserId(SysUserUtils.getUserId());
                List<TaskUser> taskUserList = taskUserService.queryFilter(filter);
                //当前任务是谁派发的
                SysUser userCreate = sysUserDao.getById(taskUserList.get(0).getCreateUser());
                //查询当前单位主要领导
                SysUserFilter userFilter = new SysUserFilter();
                userFilter.setDeptId(SysUserUtils.getDeptId());
                userFilter.setRoleId("02");
                List<String> strings = sysLoginDao.queryLoginByRoleDept(userFilter);
                //去重
                HashSet<SysUser> sysUsers = new HashSet<>();
                for (String string : strings) {
                    SysUser user = sysUserDao.getById(string);
                    sysUsers.add(user);
                }
                SysUser createUser = sysUserDao.getById(userCreate.getSysId());
                sysUsers.add(createUser);
                for (SysUser sysUser : sysUsers) {
                    if (ObjectUtils.isBlank(sysUser)) {
                        continue;
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put("userId", sysUser.getUserId());
                    map.put("username", sysUser.getName());
                    list.add(map);
                }
            }
        }
        return list;
    }

    public List<TaskUnit> getNowUnit(TaskUnitFilter filter) {
        return taskUnitDao.getNowUnit(filter);
    }

    public List<TaskUnit> getDoneUser(TaskUnitFilter filter) {
        return taskUnitDao.getDoneUser(filter);
    }

    public List<TaskUnit> getAllUser(TaskUnitFilter filter) {
        return taskUnitDao.getAllUser(filter);
    }

    public List<TaskUnit> getAllTaskUnit(TaskUnitFilter filter) {
        return taskUnitDao.queryFilter(filter);
    }

    /**
     * 返回抄送给领导的任务详情
     *
     * @param filter
     * @return
     */
    public List<TaskUnit> updateCopeTaskUnit(TaskUnitFilter filter) {
        String userId = "";
        if (StringUtils.isNotBlank(filter.getUserId())) {
            userId = filter.getUserId();
        }else{
             userId = SysUserUtils.getUserId();
        }
        filter.setUserId(null);
        TaskMain taskMain = taskMainService.getById(filter.getTaskMainId());
        //查看抄送给当前领导的任务
        List<CopeTo> copeTos = copeToService.queryByleaderIdAndTaskMainId(userId, filter.getTaskMainId());
        List<TaskUnit> taskUnits = new ArrayList<>();
        for (CopeTo copeTo : copeTos) {
            //更新当前抄送记录的状态
            //如果当前主任务是已完成
            if ("4".equals(taskMain.getStatus())) {
                //领导查看完后将抄送任务改为已办结查看
                copeTo.setStatus("3");
            } else {
                //立项抄送后的已查看
                copeTo.setStatus("1");
            }
            copeToService.update(copeTo);
            String subMainId = copeTo.getSubMainId();
            //如果抄送子任务为空。表示抄送了全部任务
            if (StringUtils.isBlank(subMainId)) {
                filter.setUserId(null);
                return taskUnitDao.queryFilter(filter);
            } else {
                filter.setTaskSubId(subMainId);
                List<TaskUnit> taskUnitList = taskUnitDao.queryFilter(filter);
                taskUnits.addAll(taskUnitList);
            }
        }
        return taskUnits;
    }

    public int getCountBySubDept(String subId, String deptId) {
        return taskUnitDao.getCountBySubDept(subId, deptId);
    }

    public List<TaskUnit> getBySubDeptIdAndTimeRound(String sysId, String deptId, int i) {
        return taskUnitDao.getBySubDeptIdAndTimeRound(sysId, deptId, i);
    }

    /**
     * 督查查看主任务中所有的单位任务中最新的
     *
     * @param filter
     * @return
     */
    public List<TaskUnit> queryTaskUnit(TaskUnitFilter filter) {
        System.out.println("===================" + filter.getTaskMainId() + "==============================");

        if (StringUtils.isNotBlank(filter.getTaskMainId())) {
            //判断当前任务是否是未审批
            TaskMain taskMain = taskMainService.getById(filter.getTaskMainId());
            System.out.println("任务名" + taskMain.getMainName());
            if ("0".equals(taskMain.getStatus())) {
                filter.setStatus("0");
            }
          /*  //如果有新反馈，只显示已经反馈的单位
            if ("3".equals(taskMain.getStatus())) {
                filter.setType("2");
            }*/
            //创建一个所有最新任务的集合
            List<TaskUnit> taskUnitList = new ArrayList<>();
            //查询当前单位任务 的子任务
            TaskSubFilter subFilter = new TaskSubFilter();
            subFilter.setTaskMainId(filter.getTaskMainId());
            List<TaskSub> taskSubList = taskSubDao.queryFilter(subFilter);
            for (TaskSub taskSub : taskSubList) {
                String subSysId = taskSub.getSysId();
                //查询当前子任务最新一轮的单位任务
                filter.setTaskSubId(subSysId);
                List<TaskUnit> subTaskUnits = taskUnitDao.getBySubIdNew(filter);
                if (ObjectUtils.isNotBlank(subTaskUnits)) {
                    taskUnitList.addAll(subTaskUnits);
                }
                //查询当前子任务最新周期前未完成的单位任务
                List<TaskUnit> subUnDoneTaskUnits = taskUnitDao.getBySubIdUnDone(filter);
                if (ObjectUtils.isNotBlank(subUnDoneTaskUnits)) {
                    taskUnitList.addAll(subUnDoneTaskUnits);
                }
            }
            if (ObjectUtils.isBlank(filter.getPaging()) || StringUtils.isBlank(filter.getPaging().getSortCol())) {
                String[] regulation = {"2", "0", "5", "3", "4"};
                final List<String> regulationOrder = Arrays.asList(regulation);
                Collections.sort(taskUnitList, new Comparator<TaskUnit>() {
                    @Override
                    public int compare(TaskUnit o1, TaskUnit o2) {
                        int io1 = regulationOrder.indexOf(o1.getType());
                        int io2 = regulationOrder.indexOf(o2.getType());
                        int i = io1 - io2;
                        if (i == 0) {
                            //按sysid降序
                            if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {
                                return 1;
                            } else {
                                return -1;
                            }
                        } else {
                            return io1 - io2;
                        }
                    }
                });
            }
            return taskUnitList;
        } else {
            return null;
        }
    }

    public List<Map<String, Object>> getByOldTaskUnit(String taskSubId, String deptId) {
        //查询当前任务进行了几轮
        int countBySubDept = taskUnitDao.getCountBySubDept(taskSubId, deptId);
        //如果任务轮次大于一轮
        if (countBySubDept > 1) {
            List<Map<String, Object>> mapList = new ArrayList<>();
            List<TaskUnit> byOldTaskUnit = taskUnitDao.getByOldTaskUnit(taskSubId, deptId, countBySubDept);
            //遍历之前的任务取出每个任务的id
            for (TaskUnit taskUnit : byOldTaskUnit) {
                //根据当前任务id查询该任务的反馈信息
                List<TaskBackNew> backNewList = taskBackNewService.getByTaskUnitId(taskUnit.getSysId());
                Map<String, Object> map = new HashMap<>();
                map.put("taskUnit", taskUnit);
                map.put("backNewList", backNewList);
                mapList.add(map);
            }
            return mapList;
        } else {
            //只有一轮就没有历史。返回null
            return null;
        }
    }

    public void saveUnit(TaskUnit taskUnit) {
        taskUnit.setSysId(tableService.updateMaxSysId("t_task_unit", null));
        taskUnitDao.save(taskUnit);
    }

    /**
     * 创建单位内部事项任务
     *
     * @param filter
     * @return
     */
    public String createTask(TaskMainFilter filter) throws ParseException {
        String userId = "";
        if (StringUtils.isBlank(filter.getUserId())) {
            userId = SysUserUtils.getUserId();
        } else {
            userId = filter.getUserId();
        }
        SysLogin login = sysLoginDao.getById(userId);
        int year = Calendar.getInstance().get(Calendar.YEAR);//年
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;//月
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);//日
        SysUser user = sysUserDao.getById(userId);
        //清空当前类型不存在的字段内容
        if (!"20190807100000000002".equals(filter.getCategoryId())) {
            filter.setFileNumber(null);//文号
        }
        if (!"20190919100000000001".equals(filter.getCategoryId())) {
            filter.setOverdueDept(null);// 单位重大事项类型的负责督查的单位
        }
        TaskMain taskMain = new TaskMain();
        //将参数赋值
        BeanUtils.copyProperties(filter, taskMain);
        taskMain.setStatus("2");//正常待完成；
        taskMain.setCategoryId("20191022100000000002");//默认为 单位内部事项
        //设置创建任务单位id（按照张宇的要求 ，现在改为科室id？？）
        taskMain.setInspectionId(login.getDeptId());
        taskMainService.save(taskMain, userId);
        //取出子事项集合
        List<TaskSubFilter> taskSubFilterList = filter.getTaskSubFilterList();
        int i = 0;//记录单位任务数量
        if (taskSubFilterList == null || taskSubFilterList.size() <= 0) {
            if (filters != null && filters.size() > 0) {
                taskSubFilterList = filters;
            } else {
                return "请添加事项";
            }
        }
        int a = 0;
        if (taskSubFilterList != null && taskSubFilterList.size() > 0) {
            for (TaskSubFilter taskSubFilter : taskSubFilterList) {
                if (StringUtils.isBlank(taskSubFilter.getUserIds())) {
                    continue;
                }
                a++;
                TaskSub taskSub = new TaskSub();
                taskSub.setStatus(taskMain.getStatus());//子任务状态与主任务相同
                taskSub.setTaskMainId(taskMain.getSysId());
                if (StringUtils.isBlank(taskSubFilter.getSubName())) {
                    //如果子事项名称为空，将主任务名称赋值到子任务名字
                    taskSub.setSubName(filter.getMainName());
                } else {
                    taskSub.setSubName(taskSubFilter.getSubName());
                }
                if (StringUtils.isBlank(taskSubFilter.getSubTimeLimit())) {
                    //如果子事项时限为空，将主任务时限赋值到子任务
                    if ("1".equals(filter.getTimeType())) {
                        //时限
                        taskSub.setTimeType("1");
                        taskSub.setSubTimeLimit(filter.getTimeLimit());
                    } else if ("2".equals(filter.getTimeType())) {
                        taskSub.setTimeType("2");
                        taskSub.setPeriod(filter.getPeriod());
                        taskSub.setDay(filter.getDay());
                        taskSub.setWeek(filter.getWeek());
                        taskSub.setMonth(filter.getMonth());
                        taskSub.setQuarter(filter.getQuarter());
                    } else {
                        taskSub.setTimeType("3");
                        taskSub.setTimeLimits(filter.getTimeLimits());
                    }
                } else {
                    //单时限
                    taskSub.setTimeType("1");
                    taskSub.setSubTimeLimit(taskSubFilter.getSubTimeLimit());
                }
                taskSubService.save(taskSub, userId);
                TimeLimit timeLimit = new TimeLimit();
                timeLimit.setTaskSubId(taskSub.getSysId());
//                timeLimit.setTaskUnitId(taskUnit.getSysId());
                timeLimit.setTimeType(taskSub.getTimeType());
                timeLimit.setPeriod(taskSub.getPeriod());
                timeLimit.setTimeLimit(taskSub.getSubTimeLimit());
                timeLimit.setTimeLimits(taskSub.getTimeLimits());
                timeLimit.setDay(taskSub.getDay());
                timeLimit.setWeek(taskSub.getWeek());
                timeLimit.setMonth(taskSub.getMonth());
                timeLimit.setQuarter(taskSub.getQuarter());
                timeLimit.setState("1");
                timeLimitService.save(timeLimit, userId);

                SysDept dept = sysDeptService.getById(login.getDeptId());
                TaskUnit taskUnit = new TaskUnit();
                taskUnit.setDeptId(dept.getSysId());
                taskUnit.setUnitType("1");//牵头单位
                taskUnit.setTaskMainName(taskMain.getMainName());
                taskUnit.setTaskSubId(taskSub.getSysId());
                taskUnit.setType("0");
                taskUnit.setTaskMainId(taskMain.getSysId());
                taskUnit.setTaskSubName(taskSub.getSubName());
                taskUnit.setStatus(taskSub.getStatus());
                if ("1".equals(taskSub.getTimeType())) {
//                            单时限
                    taskUnit.setTimeType("1");
                    taskUnit.setTimeLimit(taskSub.getSubTimeLimit());
                    taskMain.setTimeLimit(taskSub.getSubTimeLimit());
                } else if ("2".equals(taskSub.getTimeType())) {
                    //周期性
                    taskUnit.setTimeType("2");
                    taskUnit.setPeriod(taskSub.getPeriod());
                    taskUnit.setWeek(taskSub.getWeek());
                    taskUnit.setMonth(taskSub.getMonth());
                    if ("0".equals(taskSub.getPeriod())) {
                        //如果是按天的周期性反馈。
                        int dayInt = Integer.parseInt(taskSub.getDay());
                        long millis = System.currentTimeMillis();//当前时间的毫秒值
                        long timeLimitIong = millis + dayInt * 3600 * 24 * 1000;
                        String timeLimitDay = simdate1.format(timeLimitIong);//当前任务时限
                        taskUnit.setTimeLimit(timeLimitDay);
                        taskMain.setTimeLimit(timeLimitDay);
                    } else if ("1".equals(taskSub.getPeriod())) {
                        //如果是每周获取当前日期是周几
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(new Date());
                        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
                        if (w < 0) {
                            w = 7;
                        }
                        //判断周期性与当前星期的大小
                        if (w < Integer.parseInt(taskSub.getWeek())) {
                            //如果小于，时限为本周周几
                            Map<String, String> weekDate = WeekDayUtil.getWeekDate();
                            String[] dates = WeekDayUtil.getDates(weekDate.get("mondayDate"), weekDate.get("sundayDate"), taskSub.getWeek());
                            taskUnit.setTimeLimit(dates[0]);
                            taskMain.setTimeLimit(dates[0]);
                        } else {
                            //如果相同或者大于。时限为下周周几
                            Date now = new Date();
                            Map<String, String> nextWeek = WeekDayUtil.getNextWeek(simdate1.format(now));
                            String[] dates = WeekDayUtil.getDates(nextWeek.get("beginDateNext"), nextWeek.get("endDateNext"), taskSub.getWeek());
                            taskUnit.setTimeLimit(dates[0]);
                            taskMain.setTimeLimit(dates[0]);
                        }
                    } else if ("2".equals(taskSub.getPeriod())) {
                        String yearStr = year + "";
                        String monthStr = month + "";
                        String dayStr = day + "";
                        if (month < 10) {
                            monthStr = 0 + monthStr;
                        }
                        if (day < 10) {
                            dayStr = 0 + dayStr;
                        }
                        //判断当前日期与周期的日期大小
                        if (day < Integer.parseInt(taskSub.getMonth())) {
                            //如果小于。时限为本月日期
                            String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                            taskUnit.setTimeLimit(time);
                            taskMain.setTimeLimit(time);
                        } else {
                            //不小于就是下月日期
                            if (month == 12) {
                                year = year + 1;
                                String time = year + "-01-" + taskSub.getMonth();
                                taskUnit.setTimeLimit(time);
                            } else {
                                month = month + 1;
                                if (month < 10) {
                                    monthStr = "0" + month;
                                }
                                String time = year + "-" + monthStr + "-" + taskSub.getMonth();
                                taskUnit.setTimeLimit(time);
                                taskMain.setTimeLimit(time);
                            }
                        }
                    } else {
                        //每季度
                        //第一个反馈时限
                        taskUnit.setTimeLimit(taskSub.getQuarter());
                        taskMain.setTimeLimit(taskSub.getQuarter());
                    }
                } else {
                    //多时限
                    taskUnit.setTimeType("3");
                    taskUnit.setTimeLimits(taskSub.getTimeLimits());
                    //取出当前多时限的的第一个时限
                    if (taskSub.getTimeLimits().contains(",")) {
                        String[] split = taskSub.getTimeLimits().split(",");
                        taskUnit.setTimeLimit(split[0]);
                        taskMain.setTimeLimit(split[0]);
                    } else {
                        //只选择了一个
                        taskUnit.setTimeLimit(taskSub.getTimeLimits());
                        taskMain.setTimeLimit(taskSub.getTimeLimits());
                    }
                }
                taskUnit.setDeptName(dept.getDeptName());
                //设置为在办
                taskUnit.setState("1");
                //第一轮
                taskUnit.setTimeRound("1");
                taskUnit.setCategoryId(taskMain.getCategoryId());
                this.save(taskUnit, userId);


                //发送短信。查询当前单位的领导
               /*     SysUserFilter userFilter = new SysUserFilter();
                    userFilter.setRoleId("02");
                    userFilter.setDeptId(dept.getSysId());
                    List<SysLogin> loginList = sysLoginDao.queryUserLoginByRoleDept(userFilter);
                    for (SysLogin sysLogin : loginList) {
                        SysUser sysUser = sysUserDao.getById(sysLogin.getSysId());
                        String mobile = sysUser.getMobile();
                        if (StringUtils.isNotBlank(mobile)) {
                            smsUtilService.taskNewSmsService(taskUnit,  sysUser);
                        }
                    }*/
                i++;
                //记录任务流程
                if (StringUtils.isNotBlank(filter.getAuditorId())) {
                    TaskLogNew taskLogNew = new TaskLogNew();
                    taskLogNew.setTaskUnitId(taskUnit.getSysId());
                    SysUser auditor = sysUserDao.getById(filter.getAuditorId());
                    String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + auditor.getName() + "审批";
                    taskLogNew.setContent(s);
                    taskLogNewService.save(taskLogNew, userId);

                }
                if (ObjectUtils.isNotBlank(filter.getCopeToIds())) {
                    List<String> copeToIds = filter.getCopeToIds();
                    String names = "";
                    for (String copeToId : copeToIds) {
                        if (StringUtils.isNotBlank(copeToId)) {
                            String[] splitIds1 = copeToId.split(",");
                            for (String s : splitIds1) {
                                SysUser copeTo = sysUserDao.getById(s);
                                String name = copeTo.getName();
                                names = names + name + " ";
                            }
                        }

                    }
                    TaskLogNew taskLogNew = new TaskLogNew();
                    String s = user.getName() + "立项：" + taskSub.getSubName() + ",抄送领导：" + names;
                    taskLogNew.setContent(s);
                    taskLogNewService.save(taskLogNew, userId);


                }
                TaskLogNew taskLogNew = new TaskLogNew();
                taskLogNew.setTaskUnitId(taskUnit.getSysId());
                String s = user.getName() + "立项：" + taskSub.getSubName() + ",由" + dept.getDeptName() + "牵头";
                taskLogNew.setContent(s);
                taskLogNewService.save(taskLogNew, userId);

                String userIds = taskSubFilter.getUserIds();
                if (StringUtils.isBlank(userIds)) {
                    return "请添加批转人员";
                } else {
                    String[] strings = userIds.split(",");
                    for (String string : strings) {
                        {
                            //查询当前人员是否有已有任务
                            List<TaskUser> taskUserList = taskUserService.getByTaskUnitIdAndUnitUserId(taskUnit.getSysId(), string);
                            if (ObjectUtils.isNotBlank(taskUserList)) {
                                continue;
                            } else {
                                SysUser user1 = sysUserDao.getById(string);

                                TaskUser taskUser = new TaskUser();
                                taskUser.setStatus("0");
                                taskUser.setUnitUserId(string);
                                taskUser.setTaskUnitId(taskUnit.getSysId());
                                taskUser.setTaskSubId(taskUnit.getTaskSubId());
                                taskUser.setUserName(user1.getName());
                                //批转后设置人员任务为待办
                                taskUser.setStatus("0");
                                taskUser.setState("0");
                                taskUser.setCategoryId(taskMain.getCategoryId());
                                taskUserService.save(taskUser, userId);
                                //给批转人员送短信提醒
                                smsUtilService.taskUserSMS(taskUnit, user1);
                                //添加任务日志
                                taskLogNew = new TaskLogNew();
                                taskLogNew.setTaskUnitId(filter.getSysId());
                                taskLogNew.setUserId(string);
                                String content = user.getName() + "签收,批转给" + user1.getName();
                                taskLogNew.setContent(content);
                                taskLogNewService.save(taskLogNew, userId);
                            }
                        }
                    }

                        taskUnit.setType("1");
                        //单位任务转为在办

                    taskUnit.setState("1");
                    this.update(taskUnit);
                    int t0 = taskUnitDao.getCountByType(taskMain.getSysId(), "0");
                    int t1 = taskUnitDao.getCountByType(taskMain.getSysId(), "1");
                    int t2 = taskUnitDao.getCountByType(taskMain.getSysId(), "2");
                    int t3 = taskUnitDao.getCountByType(taskMain.getSysId(), "3");
                    int t4 = taskUnitDao.getCountByType(taskMain.getSysId(), "4");
                    int o = taskUnitDao.getCountByStatus(taskMain.getSysId(), "10");
                    taskMain.setTypeExplain("待签收: " + t0 + "; 待反馈: " + t1 + "; 已反馈: " + t2 + "; 重办: " + t3 + "; 完成: " + t4);
                    taskMain.setOverdueExplain("逾期单位任务: " + o);
                    taskMainService.update(taskMain);
//                    return "200";
                }
            }
            if (a <= 0) {
                return "请添加任务";
            } else {
                return "200";
            }
        } else {
            return "请添加任务";
        }
    }

    private List<TaskSubFilter> filters = new ArrayList<>();

    public List<TaskUnit> queryStatistics(TaskUnitFilter taskUnitFilter) {
        return taskUnitDao.queryStatistics(taskUnitFilter);
    }

    public List<TaskUnit> queryDateFilter(TaskUnitFilter taskUnitFilter) {
        return taskUnitDao.queryDateFilter(taskUnitFilter);
    }

    public List<TaskUnit> getByMainIdOneRound(String taskMainId) {
        return taskUnitDao.getByMainIdOneRound(taskMainId);
    }
 /*   public int getMaxValue(){
        return taskUnitDao.getMaxValue();
    }*/
}
